#include "cfontmanager.h"

CFontManager::CFontManager()
{

}

CFontManager::~CFontManager()
{
    FT_Error err;

    for (size_t i = 0; i < m_fonts.size(); i++)
    {
         delete m_fonts[i];
         m_fonts[i] = 0x00;
    }

    m_fonts.clear();

    if ((err = FT_Done_FreeType(m_library)) != FT_Err_Ok)
    {
         printf("FT_Done_FreeType() Error %d\n");
    }
}

int CFontManager::initialize(const char *path)
{
    FT_Error err;

    if ((err = FT_Init_FreeType(&m_library)) != FT_Err_Ok)
    {
        printf("FT_Init_FreeType() Error %d\n", err);
        return -1;
    }

    m_fontPath = path;
    return 0;
}


/**
 * @brief 
 * 
 * @param filename 
 * @param face 
 * @param tall 
 * @param bold 
 * @param italic 
 * @param antialias 
 * @return int 
 */
int CFontManager::createFont(const char* filename, int face, int tall, bool bold, bool italic, bool antialias)
{
    CFont* font = new CFont();

    if (font->create(m_library, filename, face, tall, bold, italic, antialias) != true)
    {
        if (font != 0x00) {
            delete font;
            font = 0x00;
        }
        return -1;
    }

    m_fonts.push_back(font);

    return 0;
}


int CFontManager::getFontTall(int font_index)
{
    int i = CONVERT_FONT_INDEX(font_index);

    if (i == -1)
    {
        return 0;
    }

    CFont *font = m_fonts[i];

    return font->getFontTall();
}



void CFontManager::renderChar(int font_index, int code, unsigned char *screen, Vec2i& position, Color color)
{

    int i = CONVERT_FONT_INDEX(font_index);

    if (i == -1)
    {
        printf("error font index!\n");
        return ;
    }

    CFont *font = m_fonts[i];
    font->setColor(color);

    switch (code) {

    case 10: {
        position[1] += font->getFontTall();
        position[0]  = m_start[0];
        break;
    }
    default:
        glyphMetrics* metrics = new glyphMetrics;
        font->renderChar(code, metrics, screen, position);
        if (metrics != 0x00)
            delete metrics;
        break;
    }

}

int CFontManager::getFontIndex(string name, int fontSize)
{
    for (int i = 0; i < m_fonts.size(); i++) {
        if (m_fonts[i]->getFontTall() == fontSize && name.compare(m_fonts[i]->fontName()) == 0)
            return i + 1;
    }
    string path = m_fontPath + name + ".TTF";
    createFont(path.c_str(), 0, fontSize, 0, 0, 1);
    return m_fonts.size() - 1;
}

void CFontManager::setStartPosition(Vec2i pos)
{
    memcpy(&m_start, &pos, sizeof(pos));
}




